<template>
  <el-upload
    class="avatar-uploader"
    :action="uploadUrl"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
    <div v-if="imageSrc" class="img-box" :style="imgBox"></div>
    <i v-else class="el-icon-plus avatar-uploader-icon" :style="iconBox"></i>
  </el-upload>
</template>
<script>
// import { uploadImgUrl } from '@/api/upload.js'

export default {
  name: 'UploadImg',
  props: {
    // 容器宽
    containerWidth: {
      type: String,
      default: '178px'
    },
    // 容器高
    containerHeight: {
      type: String,
      default: '178px'
    },
    // 图片地址
    imageSrc: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      // 上传地址
      uploadUrl: 'uploadImgUrl',
      imageUrl: ''
    }
  },
  computed: {
    iconBox () {
      console.log(this.containerWidth, this.containerHeight)
      return {
        width: this.containerWidth,
        height: this.containerHeight
      }
    },
    imgBox () {
      return {
        width: this.containerWidth,
        height: this.containerHeight,
        backgroundImage: `url('${this.imageSrc}')`
      }
    }

  },
  methods: {
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleAvatarSuccess (res) {
      console.log(res)
      if (res.code === '0000') {
        const { filePath } = res.data
        // this.imageUrl = filePath
        this.$emit('update:imageSrc', filePath)
      }
    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    padding: 5px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .img-box {
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center center;
  }
}
</style>
